FROM php:8.3-apache

ARG BUILD_ENV=prod

WORKDIR /app

ENV APACHE_DOCUMENT_ROOT /app/public

COPY debian.sources /etc/apt/sources.list.d/
RUN apt-get update && \
    apt-get -y install libwebp-dev \
    libjpeg-dev \
    libpng-dev \
    libfreetype6-dev \
    libzip-dev \
    sudo \
    cron

RUN docker-php-ext-configure gd \
    --with-jpeg=/usr/include \
    --with-freetype=/usr/include/ && \
    docker-php-ext-install gd && \
    docker-php-ext-enable gd
RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli
RUN docker-php-ext-install pdo_mysql && docker-php-ext-enable pdo_mysql
RUN docker-php-ext-install zip && docker-php-ext-enable zip
RUN docker-php-ext-install bcmath && docker-php-ext-enable bcmath
RUN pecl install redis && docker-php-ext-enable redis

COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer
COPY composer.json composer.lock ./
RUN composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ && \
    composer install \
    --ignore-platform-reqs \
    --no-interaction \
    --no-plugins \
    --no-scripts \
    --prefer-dist

RUN (crontab -l; echo "* * * * * /usr/local/bin/php /app/artisan schedule:run | sed -e '/No scheduled commands are ready to run\./d' | sed -e '/^[ ]*$/d' >> /app/storage/logs/cron.log") | crontab -u www-data -

RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf && \
    sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf && \
    sed -i -e '/DocumentRoot ${APACHE_DOCUMENT_ROOT}/a LimitRequestLine 1024000000' /etc/apache2/sites-available/*.conf
RUN cd /etc/apache2/mods-enabled/ && \
    ln -s ../mods-available/rewrite.load && \
    ln -s ../mods-available/headers.load

RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" && \
    sed -i -e 's/post_max_size = 8M/post_max_size = 10M/' "$PHP_INI_DIR/php.ini" && \
    sed -i -e 's/upload_max_filesize = 2M/upload_max_filesize = 10M/' "$PHP_INI_DIR/php.ini" && \
    printf '[PHP]\ndate.timezone = Asia/Shanghai\n' > /usr/local/etc/php/conf.d/tzone.ini

VOLUME ./storage/app/public

COPY . .
RUN if [ "${BUILD_ENV}" = 'prod' ]; then rm -rf .git; fi

RUN chown -R www-data:www-data ./storage && \
    php artisan package:discover && \
    php artisan storage:link --relative

RUN sed -i -e '/^exec/i chown www-data:www-data /app/storage/app/public' /usr/local/bin/apache2-foreground && \
    sed -i -e '/^exec/i chown -R www-data:www-data /app/storage/logs' /usr/local/bin/apache2-foreground && \
    sed -i -e '/^exec/i cron' /usr/local/bin/apache2-foreground && \
    sed -i -e '/^exec/i sudo -u www-data php artisan queue:work \&' /usr/local/bin/apache2-foreground

EXPOSE 80

CMD ["apache2-foreground"]
